package com.components.base

import android.view.ViewGroup
import androidx.fragment.app.*
import androidx.viewpager.widget.ViewPager

class BaseFragmentAdapter<F : Fragment>(private val mFragmentManager: FragmentManager) :
    FragmentPagerAdapter(mFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
    /** Fragment 集合  */
    private val mFragmentSet: MutableList<F> = ArrayList()

    /** Fragment 标题  */
    private val mFragmentTitle: MutableList<CharSequence?> = ArrayList()
    /**
     * 获取当前的Fragment
     */
    /** 当前显示的Fragment  */
    var showFragment: F? = null
        private set

    /** 当前 ViewPager  */
    private var mViewPager: ViewPager? = null

    /** 设置成懒加载模式  */
    private var mLazyMode = false
    private var mCurTransaction: FragmentTransaction? = null

    override fun getItem(position: Int): Fragment {
        return mFragmentSet[position]
    }

    override fun getCount(): Int {
        return mFragmentSet.size
    }

    override fun getPageTitle(position: Int): CharSequence? {
        return mFragmentTitle[position]
    }

    override fun setPrimaryItem(container: ViewGroup, position: Int, `object`: Any) {
        if (showFragment !== `object`) {
            // 记录当前的Fragment对象
            showFragment = `object` as F
        }
        super.setPrimaryItem(container, position, `object`)
    }

    /**
     * 添加 Fragment
     */
    @JvmOverloads
    fun addFragment(fragment: F, title: CharSequence? = null) {
        mFragmentSet.add(fragment)
        mFragmentTitle.add(title)
        if (mViewPager != null) {
            notifyDataSetChanged()
            if (mLazyMode) {
                mViewPager!!.offscreenPageLimit = count
            }
        }
    }

    override fun startUpdate(container: ViewGroup) {
        super.startUpdate(container)
        if (container is ViewPager) {
            // 记录绑定 ViewPager
            mViewPager = container
            refreshLazyMode()
        }
    }

    /**
     * 设置懒加载模式
     */
    fun setLazyMode(lazy: Boolean) {
        mLazyMode = lazy
        refreshLazyMode()
    }

    /**
     * 刷新加载模式
     */
    private fun refreshLazyMode() {
        if (mViewPager == null) {
            return
        }
        if (mLazyMode) {
            // 设置成懒加载模式（也就是不限制 Fragment 展示的数量）
            mViewPager!!.offscreenPageLimit = count
        } else {
            mViewPager!!.offscreenPageLimit = 1
        }
    }

    /**
     * 清除缓存fragment
     * 该方法解决Fragment already added
     * @param container ViewPager
     */
    fun clear(container: ViewGroup) {
        if (this.mCurTransaction == null) {
            this.mCurTransaction = this.mFragmentManager.beginTransaction()
        }
        for (i in mFragmentSet.indices) {
            val itemId = getItemId(i)
            val name = makeFragmentName(container.id, itemId)
            val fragment = this.mFragmentManager.findFragmentByTag(name)
            if (fragment != null) {
                //根据ID删除fragment，
                mCurTransaction!!.remove(fragment)
            }
        }
        mCurTransaction!!.commitNowAllowingStateLoss()
    }

    /**
     * 父类的该方法是私有的，故重新定义
     *
     */
    private fun makeFragmentName(viewId: Int, id: Long): String {
        return "android:switcher:$viewId:$id"
    }
}